<script setup lang="ts">
import {
  AddDeliver,
  DeleteById,
  GetDeliverList,
  UpdateDeliver
} from "@/api/deliver";
import { message } from "@/utils/message";
import { markRaw, onMounted, Ref, ref } from "vue";
import { ElInput, ElMessage, ElMessageBox } from "element-plus";
import { Delete } from "@element-plus/icons-vue";
import { DeliverInfo, DeliverQueryRequest } from "@/model/deliver";
import { Page } from "@/model/comon";

const queryURL =
  process.env.NODE_ENV === "development"
    ? "http://localhost:8848/#/score/"
    : "http://49.234.177.196:6767/?#/score/";

defineOptions({
  name: "DeliverManage"
});

const deliverQuery: Ref<DeliverQueryRequest> = ref({
  /**
   * 当前页号
   */
  current: 1,
  /**
   * 页面大小
   */
  pageSize: 10
});

const pageDeliverList: Ref<Page<DeliverInfo>> = ref({});

// 初始化授权信息数据
const getAllDeliver = async () => {
  const res = await GetDeliverList(deliverQuery.value);
  if (res.code === 0) {
    pageDeliverList.value = res.data;
  } else {
    message(res.message, { type: "error" });
  }
};

// 删除确认框
const deleteDeliver = id => {
  ElMessageBox.confirm("注意，此操作不可撤销，是否继续？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    icon: markRaw(Delete),
    draggable: true
  })
    .then(async () => {
      // 删除授权信息
      const res = await DeleteById(id);
      if (res.code === 0) {
        message("删除成功", { type: "success" });
        getAllDeliver();
      } else {
        message(res.message, { type: "error" });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

// 编辑授权信息信息
const editFormVisible = ref(false);
const formLabelWidth = "100px";
// 当前修改授权信息
const currentDeliver = ref({} as DeliverInfo);

// 修改授权信息对话框
const oldDay = ref();
const editDeliver = (deliver: DeliverInfo) => {
  editFormVisible.value = true;
  currentDeliver.value = Object.assign({}, deliver);
  currentDeliver.value.expireTime = new Date(deliver.expireTime);
  currentDeliver.value.day =
    (new Date(deliver.expireTime) - new Date()) / (1000 * 60 * 60 * 24);
  oldDay.value = currentDeliver.value.day;
};
// 取消修改
const cancelEdit = () => {
  editFormVisible.value = false;
  currentDeliver.value = {} as DeliverInfo;
};
// 确认修改
const confirmEdit = async () => {
  const { expireTime, day } = currentDeliver.value;
  expireTime.setDate(expireTime.getDate() + (day - oldDay.value));
  currentDeliver.value.expireTime = processDate(expireTime);
  showAddDialog.value = false;
  const res = await UpdateDeliver(currentDeliver.value);
  if (res.code === 0) {
    message("修改成功", { type: "success" });
    getAllDeliver();
    cancelEdit();
  } else {
    message(res.message, { type: "error" });
  }
};
/**
 * 分页
 */
const handleSizeChange = (val: number) => {
  deliverQuery.value.pageSize = val;
  deliverQuery.value.current = 1;
  getAllDeliver();
};
const handleCurrentChange = (val: number) => {
  deliverQuery.value.current = val;
  getAllDeliver();
};

onMounted(() => {
  getAllDeliver();
});

/**
 * 新增授权信息
 */
const showAddDialog = ref(false);
const addDeliverInfo: Ref<DeliverInfo> = ref({
  expireTime: new Date(),
  sid: "",
  day: 30
});

const showAdd = () => {
  showAddDialog.value = true;
};

const closeAdd = () => {
  showAddDialog.value = false;
  addDeliverInfo.value = {
    expireTime: new Date(),
    sid: "",
    day: 30
  };
};

const confirmAdd = async () => {
  // 参数校验
  const { sid, expireTime, day } = addDeliverInfo.value;
  if (!sid || !expireTime) {
    return ElMessage.error("请填写相关数据");
  }
  expireTime.setDate(expireTime.getDate() + day);
  addDeliverInfo.value.expireTime = processDate(expireTime);
  showAddDialog.value = false;
  const res = await AddDeliver(addDeliverInfo.value);
  if (res.code !== 0) {
    return ElMessage.error(res.message);
  }
  addDeliverInfo.value = { expireTime: new Date(), sid: "", day: 30 };
  ElMessage.success("添加成功");
  await getAllDeliver();
};

const processDate = (date: Date): string => {
  const year = date.getFullYear();
  let month: string | number = date.getMonth() + 1; // 注意月份从0开始，需要加1
  let day: string | number = date.getDate();
  let hours: string | number = date.getHours();
  let minutes: string | number = date.getMinutes();
  let seconds: string | number = date.getSeconds();
  if (month < 10) {
    month = "0" + month;
  }
  if (day < 10) {
    day = "0" + day;
  }
  if (hours < 10) {
    hours = "0" + hours;
  }
  if (minutes < 10) {
    minutes = "0" + minutes;
  }
  if (seconds < 10) {
    seconds = "0" + seconds;
  }
  return (
    year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds
  );
};
</script>

<template>
  <div>
    <el-card class="box-card">
      <el-row>
        <el-col :span="6" />
        <el-col :span="6" />
        <el-col :span="10" />
        <el-col :span="2">
          <!--      新增按钮-->
          <el-button
            type="success"
            size="large"
            style="font-size: 16px"
            plain
            @click="showAdd"
            >+ 新增授权
          </el-button>
        </el-col>
      </el-row>

      <!--  展示表格-->
      <el-table
        :data="pageDeliverList?.records"
        style="width: 100%"
        table-layout="auto"
      >
        <el-table-column fixed type="index" :index="1" />
        <el-table-column prop="sid" label="学号" />
        <el-table-column label="Token链接">
          <template #default="scope">
            <el-link
              :href="queryURL + scope.row.token"
              target="_blank"
              type="primary"
              >{{ queryURL + scope.row.token }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="expireTime" label="过期时间" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="editDeliver(scope.row)"
              >编辑
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="deleteDeliver(scope.row.id)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--  底部分页选择-->
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="pageDeliverList.current"
        v-model:page-size="pageDeliverList.size"
        :page-sizes="[5, 10, 15, 20]"
        :small="false"
        :disabled="false"
        :background="false"
        layout="total, sizes, prev, pager, next, jumper"
        :page-count="parseInt(pageDeliverList.pages)"
        :total="parseInt(pageDeliverList.total)"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!--  编辑信息对话框-->
    <el-dialog
      v-model="editFormVisible"
      title="编辑授权信息信息"
      style="width: 580px"
    >
      <el-form :model="currentDeliver">
        <el-form-item label="学号" :label-width="formLabelWidth">
          <el-input v-model="currentDeliver.sid" autocomplete="off" />
        </el-form-item>
        <el-form-item label="有效期(天)" :label-width="formLabelWidth">
          <el-input-number v-model="currentDeliver.day" :min="1" :max="999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="confirmEdit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <!--    新增授权信息-->
    <el-dialog
      v-model="showAddDialog"
      title="新增授权信息"
      width="30%"
      center
      draggable
    >
      <el-form
        label-position="right"
        label-width="80px"
        :model="addDeliverInfo"
        style="max-width: 460px"
      >
        <el-form-item label="学号">
          <el-input v-model="addDeliverInfo.sid" />
        </el-form-item>
        <el-form-item label="有效期(天)">
          <el-input-number v-model="addDeliverInfo.day" :min="1" :max="999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAdd">取消</el-button>
          <el-button type="primary" @click="confirmAdd"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
